<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/index/user/userlist' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row>
      <el-col>
        <el-table
          :data="userlist.slice((page-1)*pageSize,pageSize*page)"
          class="tableinfo margintop20"
          style="width: 100%"
          stripe
          v-if="userlist"
        >
          <el-table-column label="注册时间" sortable prop="time">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.time | timeFormat }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>姓名: {{ scope.row.username }}</p>
                <p>手机号: {{ scope.row.mobile }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.username }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="身份" sortable prop="roleid">
            <template slot-scope="scope">
              <i class="el-icon-star-off"></i>
              <el-tag
                style="margin-left: 10px"
                :type=" scope.row.roleid | colortype "
              >{{ scope.row.roleid | rolename }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="EditUser(scope.row)">编辑</el-button>
              <el-popconfirm
                confirmButtonText="好的"
                cancelButtonText="不用了"
                icon="el-icon-info"
                iconColor="red"
                title="确定删除此用户吗？"
                @onConfirm="DeleteUser(scope.row)"
              >
                <el-button size="mini" type="danger" slot="reference">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="flexbox">
          <el-pagination
            background
            layout="prev, pager, next"
            @current-change="changeCurrent"
            :page-size="pageSize"
            :current-page="page"
            :total="total"
          ></el-pagination>
          <span>共 {{total}} 条数据</span>
        </div>
      </el-col>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog title="修改用户" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form
        :model="form"
        :rules="rules"
        ref="myform"
        label-width="100px"
        label-position="right"
        class="myform"
      >
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleid">
          <el-select v-model="form.roleid">
            <el-option
              v-for="(role,i) in rolelist"
              :key="i"
              :label="role.label"
              :value="role.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateById">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import { alluserinfo, deloneuser, edituser } from "@/api";
import { rolelist } from "@/utils/index";
import Vue from "vue";
import {mapState,mapMutations} from 'vuex'
export default {
  data() {
    return {
      form: {},
      // userlist: [],
      pageSize: 10,
      page: 1,
      dialogVisible: false,
      rolelist,
      rules: {
        //表单校验
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              var mobileReg = /^1(3|5|6|7|8|9)\d{9}$/;
              if (mobileReg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              var passReg = /^[A-Za-z0-9]{4,12}$/;
              if (value.length < 4) {
                callback(new Error("密码长度至少4位"));
              } else if (value.length > 12) {
                callback(new Error("密码长度最多12位"));
              } else if (!passReg.test(value)) {
                callback(new Error("密码格式不正确"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState(['userlist']),
    total() {
      return this.userlist.length;
    },
    
  },
  methods: {
    ...mapMutations(['changeUserlist']),
    EditUser(row) {
      this.dialogVisible = true; //唤起弹窗
      this.form = { ...this.form, ...row };
    },
    updateById() {
      this.$refs.myform.validate((valid) => {
        if (valid) {
          //正则通过就判断权限是否足够执行此次操作
          var roleid = sessionStorage.getItem("roleid");
          var mobile = localStorage.getItem("mobile");

          if (roleid < this.form.roleid) {
            this.$message.error("权限不足，无法执行此次操作");
          } else if (mobile == this.form.mobile) {
            this.$message.error("暂不支持此操作");
          } else {
            edituser(this.form)
              .then((res) => {
                this.dialogVisible = false;
                // this.userlist.forEach((item, i) => {
                //   if (item._id == this.form._id) {
                //     this.form.roleid = this.form.roleid + "";
                //     Vue.set(this.userlist, i, this.form);
                //   }
                // });

                this.userlist = this.userlist.map((item) => {
                  if ((item._id == this.form. _id)) {
                    this.form.roleid = this.form.roleid + "";
                    item = {...item,...this.form}
                  }
                  return item
                });
                // console.log(this.userlist);
              })
              .catch((err) => {});
          }
        } else {
          this.$message.error("输入格式不正确");
          return false;
        }
      });
    },
    changeCurrent(page) {
      this.page = page;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 删除一个用户
    DeleteUser(row) {
      // console.log(111);
      //删除用户之前要判断删除的用户的权限是否能否执行删除操作，也不能删除自己
      var roleid = sessionStorage.getItem("roleid");
      var mobile = localStorage.getItem("mobile"); //用来判断是用户本人吗
      if (roleid < row.roleid) {
        this.$message.error("权限不够无法执行此次操作");
      } else if (mobile == row.mobile) {
        //不能删除自己
        this.$message.error("暂时无法执行此操作");
      } else {
        deloneuser({
          _id: row._id,
        })
          .then((res) => {
            if (res.type) {
              // console.log(111);
              this.userlist = this.userlist.filter(
                (item) => item._id != row._id
              );
            }
          })
          .catch((err) => {});
      }
    },
  },
  mounted() {
    if(!this.userlist){
      alluserinfo()
      .then((res) => {
        if (res.type) {
          this.$nextTick(() => {
            console.log(111);
            // this.userlist = res.result;
            this.changeUserlist(res.result)
          });
        }
      })
      .catch((err) => {});
    }
  },
};
</script>